//
//  GetSectionkeyViewController.m
//  TestTaoBaoAPI
//
//  Created by ZhuoLaiQiang@Gmail.com on 6/22/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GetSectionkeyViewController.h"
#import "StaicParameter.h"
#import "NSString+Encode.h"
#import "GetLoginParameter.h"
#import "Global.h"
#import "SBJson.h"

static NSString *api = @"com.taobao.client.mtop.getUserSessionKey";

@implementation GetSectionkeyViewController

@synthesize autoLogin = _autoLogin;

- (void)dealloc
{
    [super dealloc];
    [_dic release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (NSString*)getTimeInterval
{
    NSDate *date = [NSDate date];
    NSTimeInterval time1 = [date timeIntervalSince1970];
    NSTimeInterval time2 = 1000.0 * 60.0 * 60.0 * 24.0 * 365.0 * 1970.0;
    NSTimeInterval time3 = time1 + time2;
    return [NSString stringWithFormat: @"%f", time3];
}

- (NSString*)getSign
{
    NSString *appkey = [StaicParameter getValueFormKey: @"appkey"];
    NSString *appSecret = [StaicParameter getValueFormKey: @"appSecret"];
    NSString *key = [StaicParameter getValueFormKey: @"key"];
    NSString *t = [self getTimeInterval];
    if (appSecret && appkey && key && t) {
        NSString *sign = [[[NSString stringWithFormat: @"%@%@%@%@", appkey, appSecret, key, t] md5] base64String];
        return sign;
    }
    assert(0);
    return nil;
}

- (NSString*)getData
{
    //    {"key":"29491373-2879-44e2-ab03-c50bbab3ccaa","app key":"12170061"}
    
    NSString *key = [StaicParameter getValueFormKey: @"key"];
    NSString *appkey = [StaicParameter getValueFormKey: @"appkey"];
    NSString *data = [NSString stringWithFormat: @"{\"key\":\"%@\",\"appkey\":\"%@\"}", key, appkey];
    if (data) {
        return data;
    }
    assert(0);
    return  nil;
}

- (NSString*)getParameter
{
    //_dic = [[NSMutableDictionary alloc] init];
    // [_dic setObject: api forKey: @"api"];
    NSString *imei = [StaicParameter getValueFormKey: @"imei"];
    NSString *imsi = [StaicParameter getValueFormKey: @"imsi"];
    NSString *ttid = [StaicParameter getValueFormKey: @"ttid"];
    NSString *sign = [self getSign];
    NSString *data = [self getData];
    NSString *key = [StaicParameter getValueFormKey: @"key"];
    NSString *appkey = [StaicParameter getValueFormKey: @"appkey"];
    NSString *t = [self getTimeInterval];
    
    if (api && imei && imsi && ttid && sign && data && key && appkey && t) {
        _dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys: api, @"api", imei, @"imei", imsi, @"imsi", ttid, @"ttid", sign, @"sign", data, @"data", key, @"key", appkey, @"appkey", t, @"t", nil];
        NSString *parameter = [GetLoginParameter urlString2: _dic];
        NSLog(@"%@", parameter);
        return parameter;
    }
    
    return nil;
}

- (NSString*)getRequestUrl
{
    NSString *url =  [StaicParameter getValueFormKey: @"baseAPIURL"];
    NSString *requestUrl = [NSString stringWithFormat: @"%@%@", url, [self getParameter]];
    return requestUrl;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton *button = [UIButton buttonWithType: UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 100, 100);
    [button addTarget: self action: @selector(buttonPressed) forControlEvents: UIControlEventTouchUpInside];
    [button setTitle: @"获取sectionkey" forState: UIControlStateNormal];
    [self.view  addSubview: button];
}


- (void)buttonPressed
{
    if (_autoLogin) {//如果是自动登录
      //  http://api.m.taobao.com/rest/api2.do?api=com.taobao.client.sys.autoLogin&t=20080101& v=*&data={"token":"123456","appkey":"123455","appsign":"xxxxxxxxxxxxxxxxxx"}&imei=xx xxxxxxx&imsi=xxxxxxxxxxxx
        NSString *baseUrl = [StaicParameter getValueFormKey: @"baseAPIURL"];
        NSString *api = @"com.taobao.client.sys.autologin";
        
        NSDateFormatter *dateformat = [[[NSDateFormatter alloc] init] autorelease];
        [dateformat setDateFormat:@"YYYYMMdd"];
        NSDate *date = [NSDate date];
        NSString *t = [dateformat stringFromDate: date];
        NSLog(@"%@", t);
        
        NSString *v = @"1.0";
        
        NSString *token = [StaicParameter getValueFormKey: @"token"];
        NSString *appkey = [StaicParameter getValueFormKey: @"appkey"];
        NSString *appSecret = [StaicParameter getValueFormKey: @"appSecret"];
        NSString *nick = [StaicParameter getValueFormKey: @"nick"];
        NSString *appsign = [[NSString stringWithFormat: @"%@%@%@", appkey, appSecret, nick] md5];
        NSString *data = [NSString stringWithFormat: @"{\"token\":\"%@\",\"appkey\":\"%@\",\"appsign\":\"%@\"}", token, appkey, appsign];
        NSLog(@"%@", [NSString stringWithFormat: @"{\"token\":\"%@\",\"appkey\":\"%@\",\"appsign\":\"%@\"}", token, appkey, appsign]);
        
        NSString *imei = [[GetLoginParameter getImeiImsi] objectForKey: @"imei"];
        NSString *imsi = [[GetLoginParameter getImeiImsi] objectForKey: @"imsi"];
        
        NSMutableDictionary *pDic = [NSMutableDictionary dictionaryWithObjectsAndKeys: api,@"api", t, @"t", v, @"v", data, @"data", imei, @"imei", imsi, @"imsi", nil];
        NSString *parameter = [GetLoginParameter urlString2: pDic];
        NSLog( @"%@", parameter);
        NSString *urlStr = [NSString stringWithFormat: @"%@%@", baseUrl, parameter];
        
        NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlStr]] autorelease];
         NSLog(@"%@", [[request URL] absoluteString]);
        
        NSHTTPURLResponse *response=nil; 
        NSError* error = nil;
        NSData* tempData =  [NSURLConnection sendSynchronousRequest:request  
                                              returningResponse:&response
                                                          error:&error];  
        if (error)
        {
            assert(0);
        }
        
        NSString *jsonStr = [[[NSString alloc] initWithData: tempData encoding: NSUTF8StringEncoding] autorelease];
        NSDictionary *dic = (NSDictionary*)[jsonStr JSONValue];
        NSLog(@"%@",dic);
        
        id loginUrlStr = [dic objectForKey: @"ret"];
        NSMutableString *strAll = [[[NSMutableString alloc] init] autorelease];
        
        if ([loginUrlStr isKindOfClass: [NSArray class]]) 
        {
            for (NSString *str in (NSArray *)loginUrlStr)
            {
                [strAll appendString: str];
            }
        }
        NSString *message = @"索取失败";
        if (strAll && [strAll rangeOfString: @"SUCCESS"].location != NSNotFound)
        {
            NSMutableDictionary *dataDic = [dic objectForKey: @"data"];
            NSString *token = [dataDic objectForKey: @"token"];
            NSString *sid = [dataDic objectForKey: @"sid"];
            NSString *ecode = [dataDic objectForKey: @"ecode"];
            NSString *nick = [dataDic objectForKey: @"nick"];
            NSString *topsession = [dataDic objectForKey: @"topsession"]; 
            [StaicParameter setDicWithValue: token key: @"token"];
            [StaicParameter setDicWithValue: sid key: @"sid"];
            [StaicParameter setDicWithValue: ecode key: @"ecode"];
            [StaicParameter setDicWithValue: nick key: @"nick"];
            [StaicParameter setDicWithValue: topsession key: @"topsession"];
            NSLog(@"%@", token);
            message = @"成功索取";
        }
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"提示" message: message delegate: nil cancelButtonTitle: @"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];


                
    }else {//如果不是自动登录
        
        NSString *requestUrl = [self getRequestUrl];
        
        NSLog(@"%@", requestUrl);
        
        NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: requestUrl]] autorelease];
        // NSLog(@"%@", urlStr);
        
        NSHTTPURLResponse *response=nil; 
        NSError* error = nil;
        NSData* data =  [NSURLConnection sendSynchronousRequest:request  
                                              returningResponse:&response
                                                          error:&error];  
        if (error)
        {
            assert(0);
        }
        
        NSString *jsonStr = [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
        NSDictionary *dic = (NSDictionary*)[jsonStr JSONValue];
        NSLog(@"%@",dic);
        id loginUrlStr = [dic objectForKey: @"ret"];
        NSMutableString *strAll = [[[NSMutableString alloc] init] autorelease];
        
        if ([loginUrlStr isKindOfClass: [NSArray class]]) 
        {
            for (NSString *str in (NSArray *)loginUrlStr)
            {
                [strAll appendString: str];
            }
        }
        NSString *message = @"索取失败";
        if (strAll && [strAll rangeOfString: @"SUCCESS"].location != NSNotFound)
        {
            NSMutableDictionary *dataDic = [dic objectForKey: @"data"];
            NSString *token = [dataDic objectForKey: @"token"];
            NSString *sid = [dataDic objectForKey: @"sid"];
            NSString *ecode = [dataDic objectForKey: @"ecode"];
            NSString *nick = [dataDic objectForKey: @"nick"];
            NSString *topsession = [dataDic objectForKey: @"topsession"]; 
            [StaicParameter setDicWithValue: token key: @"token"];
            [StaicParameter setDicWithValue: sid key: @"sid"];
            [StaicParameter setDicWithValue: ecode key: @"ecode"];
            [StaicParameter setDicWithValue: nick key: @"nick"];
            [StaicParameter setDicWithValue: topsession key: @"topsession"];
            NSLog(@"%@", token);
            message = @"成功索取";
        }
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"提示" message: message delegate: nil cancelButtonTitle: @"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }

    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
